package com.yznote.compileserver.controller;

import com.jcraft.jsch.Session;
import com.yznote.compileserver.pojo.Result;
import com.yznote.compileserver.terminal.TerminalClient;
import com.yznote.compileserver.terminal.TerminalConnectConfig;
import com.yznote.compileserver.terminal.TerminalSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ConcurrentHashMap;

@RestController
@Slf4j
@RequestMapping("/terminal")
public class TerminalController {
    @Autowired
    TerminalClient terminalClient;
    @Autowired
    @Qualifier("sessionPool")
    ConcurrentHashMap<Long,TerminalSession> sessionPool;
    @GetMapping("/connect")
    public Result connect(@RequestParam("userId") Long userId,@RequestParam("name") String name,@RequestParam("password") String password,@RequestParam("host") String host,@RequestParam("port") Integer port){
        log.info("{}called{}",userId,name);
        TerminalSession terminalSession = sessionPool.get(userId);
        if(terminalSession!=null) return Result.sussess(null,"用户已经连接");
        // 进行连接操作
        TerminalConnectConfig terminalConnectConfig = new TerminalConnectConfig();
        terminalConnectConfig.setUserName(name);
        terminalConnectConfig.setPort(port);
        terminalConnectConfig.setPassword(password);
        terminalConnectConfig.setConnectTimeOut(500l);
        terminalConnectConfig.setHost(host);
        try {
            Session connect = terminalClient.connect(terminalConnectConfig);
            TerminalSession terminalSession1 = TerminalSession.getTerminalSession(connect);
            sessionPool.put(userId,terminalSession1);
            return Result.sussess(null,"连接成功");
        }catch (Exception e){
            return Result.fail("连接失败");
        }
    }
    @GetMapping("/sendCmd")
    public Result sendCmd(@RequestParam("userId") Long userId,@RequestParam("cmd") String cmd){
        log.info("{}called{}",userId,cmd);
        TerminalSession terminalSession = sessionPool.get(userId);
        if(terminalSession==null) return Result.fail("用户还未进行连接");
        try {
            String s = terminalSession.sendCmd(cmd);
            return Result.sussess(s,"执行命令成功");
        }catch (Exception e) {
            return Result.fail("执行命令失败");
        }
    }

}
